package com.kgc.mall.filter;



import com.kgc.mall.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.sql.SQLException;

@WebFilter("/*")
public class OpenSessionInViewFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //创建SqlSession并在当前线程中共享
        SqlSession sqlSession = MyBatisUtil.newSession();

        try {
            filterChain.doFilter(servletRequest, servletResponse);
            //提交事务
            sqlSession.commit();
        } catch (IOException e) {
            //回滚事务
            sqlSession.rollback();
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } finally {
            //关闭当前线程共享SqlSession
            MyBatisUtil.closeSession();
        }
    }

    @Override
    public void destroy() {

    }
}
